import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
  VideoCameraOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import { Button, Layout, Menu, theme, Drawer, Space, Checkbox } from "antd";
import "./home.css";
import SysList from "../../component/sysUser";
import OaList from "../../component/oaUser";
import SysLog from "../../component/sysLog";

const { Header, Sider, Content } = Layout;

const Home = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [selectedMenuKey, setSelectedMenuKey] = useState("1");
  const navigate = useNavigate(); // 导航
  const location = useLocation(); // 获取传递过来的用户身份（地址栏信息）
  const role = location.state?.role || "logger"; // 获取到用户名，默认为 logger
  const [open, setOpen] = useState(false); // 控制抽屉
  const [size, setSize] = useState(); // 控制抽屉
  // 初始化权限
  const [permissions, setPermissions] = useState(() => {
    const storedPermissions = localStorage.getItem("permissions");
    return storedPermissions
      ? JSON.parse(storedPermissions)
      : {
          admin: { read: true, write: true, delete: true, view: true },
          maintainer: { read: true, write: false, delete: false, view: true },
          logger: { read: false, write: false, delete: false, view: true },
        };
  });

  // console.log(location);
  useEffect(() => {
    // 根据用户身份（角色）设置默认选中的菜单项
    const defaultMenuKey = getMenuItems()[0]?.key;
    setSelectedMenuKey(defaultMenuKey);
  }, [role]);

  useEffect(() => {
    // 将权限保存到本地存储中
    localStorage.setItem("permissions", JSON.stringify(permissions));
  }, [permissions]);

  // 从本地存储中获取权限列表并更新状态
  useEffect(() => {
    const storedPermissions = localStorage.getItem("permissions");
    if (storedPermissions) {
      setPermissions(JSON.parse(storedPermissions));
    }
  }, []);

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  // 根据用户身份（角色）过滤菜单项
  const getMenuItems = () => {
    const allItems = [
      {
        key: "1",
        icon: <UserOutlined />,
        label: "系统用户管理",
      },
      {
        key: "2",
        icon: <VideoCameraOutlined />,
        label: "OA用户管理",
      },
      {
        key: "3",
        icon: <UploadOutlined />,
        label: "系统日志查看",
      },
    ];

    switch (role) {
      case "admin":
        return allItems;
      case "maintainer":
        return allItems.slice(0, 2); // 返回 allItems 数组中的第一个和第二个元素。
      case "logger":
        return allItems.slice(2); // 返回 allItems 数组中的第三个元素
      default:
        return [];
    }
  };

  useEffect(() => {
    // 根据角色设置默认选中的菜单项
    const defaultMenuKey = getMenuItems()[0]?.key;
    setSelectedMenuKey(defaultMenuKey);
  }, [role]);

  useEffect(() => {
    // 将权限保存到本地存储中
    localStorage.setItem("permissions", JSON.stringify(permissions));
  }, [permissions]);

  // 渲染右侧内容部分
  const renderContent = () => {
    switch (selectedMenuKey) {
      case "1":
        return <SysList />;
      case "2":
        return <OaList />;
      case "3":
        return <SysLog />;
      default:
        return "Content";
    }
  };

  // 重设时间格式
  const date = new Date();
  const options = {
    year: "numeric",
    month: "short",
    day: "numeric",
    weekday: "short",
    hour: "numeric",
    minute: "numeric",
    second: "numeric",
  };
  const result = date.toLocaleString("zh-CN", options);

  // 退出登录
  const loginOut = () => {
    localStorage.removeItem("permissions"); // 清除本地存储中的权限信息
    const loginRecords =
      JSON.parse(window.localStorage.getItem("loginRecords")) || [];

    if (loginRecords.length === 0) {
      console.error("No login records found.");
      return;
    }

    const lastLogin = loginRecords[loginRecords.length - 1]; // 获取最后一个登入记录
    const loginOutLog = result;
    // 生成登出记录
    console.log(loginOutLog);
    // 从localStorage中取出登出记录数组
    let logoutRecords =
      JSON.parse(window.localStorage.getItem("logoutRecords")) || [];
    // 将新的登出记录添加到数组中
    logoutRecords.push({
      user: lastLogin.user,
      loginTime: lastLogin.time,
      logoutTime: loginOutLog,
    });
    // 将登出记录数组转换成字符串存入localStorage
    window.localStorage.setItem("logoutRecords", JSON.stringify(logoutRecords));

    navigate("/", { replace: true });
  };

  // 编辑用户，展示右侧抽屉
  const showDefaultDrawer = () => {
    if (role === "admin" || role === "maintainer") {
      setSize("修改权限");
      setOpen(true);
    }
  };
  const onClose = () => {
    setOpen(false);
  };

  // 更新权限
  const handlePermissionChange = (user, permission, value) => {
    setPermissions({
      ...permissions,
      [user]: {
        ...permissions[user],
        [permission]: value,
      },
    });
  };

  // 确认编辑权限
  const confirmEditPermission = () => {
    // 编辑权限的逻辑
    onClose(); // 关闭抽屉
  };

  return (
    <Layout>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="demo-logo-vertical" />
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={[selectedMenuKey]}
          selectedKeys={[selectedMenuKey]}
          onSelect={({ key }) => setSelectedMenuKey(key)}
          items={getMenuItems()} // 展示过滤后的Sider选项数量
        />
      </Sider>
      <Layout>
        <Header
          style={{
            padding: "0px",
            background: colorBgContainer,
          }}
        >
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)} // 折叠
            style={{
              fontSize: "16px",
              width: 64,
              height: 64,
            }}
          />
        </Header>
        <Content
          style={{
            margin: "24px 16px",
            padding: 24,
            minHeight: 280,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >
          {renderContent()}
        </Content>
      </Layout>
      <div className="title">用户管理后台</div>
      <Button className="loginOut" size="small" onClick={loginOut}>
        退出登录
      </Button>

      <Space>
        {(role === "admin" || role === "maintainer") && (
          // && 如果前者为false则不显示，反之true则显示后者
          <Button
            className="admin"
            type="primary"
            size="small"
            onClick={showDefaultDrawer}
          >
            管理员
          </Button>
        )}
      </Space>
      {/* 隐藏区域 */}
      <Drawer
        title={`${size} `}
        placement="right"
        size={size}
        onClose={onClose}
        open={open}
        extra={
          <Space>
            <Button onClick={onClose}>取消</Button>
            <Button type="primary" onClick={confirmEditPermission}>
              确定
            </Button>
          </Space>
        }
      >
        {/* 编辑权限的具体内容 */}
        {Object.keys(permissions).map((user) => (
          <div key={user}>
            <h3>{user}</h3>
            <Checkbox
              checked={permissions[user].read}
              onChange={(e) =>
                handlePermissionChange(user, "read", e.target.checked)
              }
            >
              读
            </Checkbox>
            <Checkbox
              checked={permissions[user].write}
              onChange={(e) =>
                handlePermissionChange(user, "write", e.target.checked)
              }
            >
              改
            </Checkbox>
            <Checkbox
              checked={permissions[user].delete}
              onChange={(e) =>
                handlePermissionChange(user, "delete", e.target.checked)
              }
            >
              删
            </Checkbox>
            <Checkbox
              checked={permissions[user].view}
              onChange={(e) =>
                handlePermissionChange(user, "view", e.target.checked)
              }
            >
              查看
            </Checkbox>
          </div>
        ))}
      </Drawer>
    </Layout>
  );
};

export default Home;
